//
//  DetailViewController.m
//  Travel
//
//  Created by 吴品泽 on 15/4/4.
//  Copyright (c) 2015年 &#21556;&#21697;&#27901;. All rights reserved.
//

#import "DetailViewController.h"
#import <AFHTTPRequestOperationManager.h>
#import <UIImageView+WebCache.h>
#import <UIButton+WebCache.h>
#import "model1.h"
#import "model2.h"
#import "model3.h"
#import "model4.h"
#import "model5.h"

#import "DetailTableViewCell.h"
#import "DetailCunImageCell.h"
#import "DetalImagAndLabelCell.h"
#import "UserViewController.h"
@interface DetailViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain)UITableView *tableView;


@property (nonatomic,retain)model1 *no1;
@property (nonatomic,retain)model2 *no2;
@property (nonatomic,retain)model3 *no3;
@property (nonatomic,retain)model4 *no4;
@property (nonatomic,retain)model5 *no5;
@property (nonatomic,assign)NSInteger count;
@property (nonatomic,retain)NSMutableArray *AllDaysArr;
@property (nonatomic,retain)NSMutableArray *Allnodes;
@property (nonatomic,retain)NSMutableArray *Anotes;

@property (nonatomic,retain)NSMutableArray *model2Arr;
@property (nonatomic,retain)NSMutableArray *model3Arr;

@property (nonatomic, strong) DetailCunImageCell *detailCunImageCell;



@property (nonatomic,strong)UIImageView *traImageView;
@property (nonatomic,strong)UILabel *titleLabel;
@property (nonatomic,retain)UILabel *timerLabel;
@property (nonatomic,retain)UIButton *userButton;
@property (nonatomic,retain)UIView *backView;

@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   // self.navigationController.navigationBarHidden = YES;
    NSLog(@".......%@",self.IDNumber);
    self.Allnodes = [NSMutableArray array];
    self.Anotes = [NSMutableArray array];
    [self requestAllData];
    [self createTableView];
    
}


- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    NSLog(@"分区的个数%ld",self.no1.trip_days.count);
    return self.no1.trip_days.count;
}
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    
//    return @"背的啊";
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(view.frame.size.width * 1.3 /4, 0, 50, 30)];

   model2 *mode = [self.no1.trip_days objectAtIndex:section];
    NSString *string = [NSString stringWithFormat:@"DAY%@",mode.day];
    label.text = string;
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake( view.frame.size.width * 1.3 / 4 + 50, 0, view.frame.size.width * 2.7 /4 - 50, 30)];
    [view addSubview:label];
    [view addSubview:label2];
    label2.font = [UIFont systemFontOfSize:15];
    label2.alpha = 0.7;
    label2.text = mode.trip_date;
   // label2.backgroundColor = [UIColor redColor];
    //label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor whiteColor];
    view.backgroundColor = [UIColor whiteColor];
    
    return view;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        _no2 = [_no1.trip_days objectAtIndex:section];
    self.model3Arr = [NSMutableArray array];

    for (model3 *n3 in _no2.nodes) {

        for (model4 *n4 in n3.notes) {
            
            [self.model3Arr addObject:n4];
        }
    }
//    NSLog(@"%@  cell的个数 %ld",_no2.trip_date,_model3Arr.count);
    return _model3Arr.count;
    

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
       _no2 = [_no1.trip_days objectAtIndex:indexPath.section];
    self.model3Arr = [NSMutableArray array];
    
    for (model3 *n3 in _no2.nodes) {
        
        for (model4 *n4 in n3.notes) {
            
       [self.model3Arr addObject:n4];
            
            
        }
    }
    
    model4 *mo = [self.model3Arr objectAtIndex:indexPath.row];
    
//    NSLog(@"^^^^^^^^^^%@",mo.Adescriptions);
    
    //有图片有字的时候
    if ( (mo.photo != nil ) && ![mo.Adescriptions isEqualToString:@""]) {
        
        
        static NSString *str = @"hehe1";
        DetalImagAndLabelCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[DetalImagAndLabelCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
        }

        
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
        
        CGRect rect = [mo.Adescriptions boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        NSNumber *wide =  [mo.photo objectForKey:@"image_width"];
        NSNumber *height = [mo.photo objectForKey:@"image_height"];
        
        NSInteger wi = [wide integerValue];
        NSInteger hi = [height integerValue];
        
        CGFloat  EndHight = hi * self.view.frame.size.width  * 1.0 / wi;
        
        cell.MYimageView.frame = CGRectMake(10, 10, self.view.frame.size.width - 20, EndHight - 20);
        cell.deLabel.frame = CGRectMake(10,  EndHight - 10 , self.view.frame.size.width - 20, rect.size.height + 20);
      //  NSLog(@"%ld---%g   %g %g %g",indexPath.row,cell.deLabel.frame.size.width,cell.deLabel.frame.origin.x,cell.contentView.frame.size.width,cell.frame.size.width);
        NSURL *url = [NSURL URLWithString:[mo.photo objectForKey:@"url"]];
        [cell.MYimageView sd_setImageWithURL:url placeholderImage:nil];
        
        cell.deLabel.text = mo.Adescriptions;
        cell.deLabel.font = [UIFont systemFontOfSize:15];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
       
        //纯文字的时候
    }else if (![mo.Adescriptions isEqualToString:@""] && (mo.photo == nil ))
    {
        
        
        static NSString *str = @"hehe";
        DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[DetailTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
        }
       

          cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
        CGRect rect = [mo.Adescriptions boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        cell.Detaillabel.frame = CGRectMake(10, 10, self.view.frame.size.width - 20,  rect.size.height + 10);
        
        cell.Detaillabel.font = [UIFont systemFontOfSize:15];
        cell.Detaillabel.text =mo.Adescriptions;
        
        return cell;
        
        //纯图片的时候
    }else if ([mo.Adescriptions isEqualToString:@""]){
        
        static NSString *str = @"hehe2";
        NSLog(@"indexPath:%ld %ld",indexPath.row,indexPath.section);
        DetailCunImageCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[DetailCunImageCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
        }
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSNumber *wide =  [mo.photo objectForKey:@"image_width"];
        NSNumber *height = [mo.photo objectForKey:@"image_height"];
        
        NSInteger wi = [wide integerValue];
        NSInteger hi = [height integerValue];
        NSLog(@"________________%ld,%ld",indexPath.section,indexPath.row);

        CGFloat  EndHight = hi * self.view.frame.size.width  * 1.0 / wi;
        
        
        if (mo.photo != nil && mo.video == nil) {
            
           
            cell.MyimageView.frame = CGRectMake(10, 10, self.view.frame.size.width - 20, EndHight );
            
            NSURL *url = [NSURL URLWithString:[mo.photo objectForKey:@"url"]];
            [cell.MyimageView sd_setImageWithURL:url placeholderImage:nil];

        }
        
        return cell;
    }

    static NSString *str = @"hehe4";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    _no2 = [_no1.trip_days objectAtIndex:indexPath.section];
    self.model3Arr = [NSMutableArray array];
    
    for (model3 *n3 in _no2.nodes) {
        
        for (model4 *n4 in n3.notes) {
            
            [self.model3Arr addObject:n4];
            
            
        }
    }
    
    model4 *mo = [self.model3Arr objectAtIndex:indexPath.row];
    NSLog(@"mo:%@",mo.Adescriptions);
    NSLog(@"photo:%@",mo.photo);
    
    //图片加文字
    if ( (mo.photo != nil ) && ![mo.Adescriptions isEqualToString:@""] && mo.video == nil) {
        
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
        
        CGRect rect = [mo.Adescriptions boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        NSNumber *wide =  [mo.photo objectForKey:@"image_width"];
        NSNumber *height = [mo.photo objectForKey:@"image_height"];
        
        NSInteger wi = [wide integerValue];
        NSInteger hi = [height integerValue];
        
        CGFloat  EndHight = hi * self.view.frame.size.width  * 1.0 / wi;
        
      //  NSLog(@"1:%.2f", rect.size.height + EndHight + 20);
        return rect.size.height + EndHight + 20;
        
        //纯文字
    }
    if (![mo.Adescriptions isEqualToString:@""] && (mo.photo == NULL ) && mo.video == nil)
    {
         NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
        CGRect rect = [mo.Adescriptions boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
     //   NSLog(@"2:%.2f", rect.size.height +30);

        return rect.size.height + 30;
        
        //纯图片
    }
    if ([mo.Adescriptions isEqualToString:@""] && mo.photo != nil && mo.video == nil ){
        
        NSNumber *wide =  [mo.photo objectForKey:@"image_width"];
        NSNumber *height = [mo.photo objectForKey:@"image_height"];
        
        NSInteger wi = [wide integerValue];
        NSInteger hi = [height integerValue];
    //    NSLog(@"wi:%d hi:%d",wi,hi);
        CGFloat  EndHight = hi * self.view.frame.size.width *1.0  / wi;
     //   NSLog(@"indexPath:%d %d",indexPath.row,indexPath.section);

      //  NSLog(@"%f",EndHight);
       NSLog(@"3:%.2f", EndHight + 30);

        return EndHight + 30;
    }
    
    if ([mo.Adescriptions isEqualToString:@""] && mo.video != nil) {
     
        return 0;
    }
        
    
    
    return 0;
    

}


- (void)requestAllData
{
    NSString *str1 = [NSString stringWithFormat:@"%@",self.IDNumber];
    NSString *string = [NSString stringWithFormat:@"https://chanyouji.com/api/trips/%@.json",str1];
    NSLog(@">>>>>>>>>%@",string);
//    NSMutableArray *array1 = [NSMutableArray array];
//    NSMutableArray *array2 = [NSMutableArray array];
//    NSMutableArray *array3 = [NSMutableArray array];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:string parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //数据获取
        //创建一个数组来接model1
        self.AllDaysArr = [NSMutableArray array];

        self.no1 = [[model1 alloc]init];
        [self.no1 setValuesForKeysWithDictionary:responseObject];
        [self.no1 getmodel2];
        _AllDaysArr = self.no1.trip_days;
        for (model2 *n2 in self.no1.trip_days) {
            [n2 getmodel3];
            for (model3 *n3 in n2.nodes) {
                
                [n3 getmodel4];
//                NSLog(@"%ld",n3.notes.count);
            }
        }
        
        
        
       // NSLog(@"???????%@",self.no1.front_cover_photo_url);
        UIImageView *headView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT * 0.3)];
        NSURL *urlimage = [NSURL URLWithString:self.no1.front_cover_photo_url];
#pragma 占位图没加
        headView.userInteractionEnabled = YES;
        [headView sd_setImageWithURL:urlimage placeholderImage:nil];
       // headView.backgroundColor = [UIColor yellowColor];
        self.timerLabel = [[UILabel alloc]init];
        self.titleLabel = [[UILabel alloc]init];
        // self.traImageView.backgroundColor = [UIColor blackColor];
        self.titleLabel.numberOfLines = 0;
        self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
        self.titleLabel.frame = CGRectMake(headView.frame.size.width / 5, headView.frame.size.height - 60 , headView.frame.size.width - 20,30);
        self.titleLabel.textColor = [UIColor whiteColor];
        //self.titleLabel.backgroundColor = [UIColor yellowColor];
        
        self.timerLabel.frame = CGRectMake(headView.frame.size.width / 5,headView.frame.size.height - 30 , headView.frame.size.width - 20 , 20);
      self.timerLabel.textColor = [UIColor whiteColor];
        self.timerLabel.font = [UIFont systemFontOfSize:15];
        //self.timerLabel.backgroundColor = [UIColor redColor];
        self.userButton = [[UIButton alloc]init];
        self.userButton.frame = CGRectMake(10, headView.frame.size.height - 60, 50, 50);
       // self.userButton.backgroundColor = [UIColor redColor];
        self.userButton.layer.masksToBounds = YES;
        self.userButton.layer.cornerRadius = 25;
        [self.userButton addTarget:self action:@selector(clickUser:) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        self.titleLabel.text = self.no1.name;
        NSInteger number = self.no1.trip_days.count;
        NSString *strings = [NSString stringWithFormat:@"%@ / %ld天/ %@图",self.no1.start_date,number,self.no1.photos_count];
        
        self.timerLabel.text = strings;
        
        NSURL *urls = [NSURL URLWithString:[self.no1.user objectForKey:@"image"]];
        
#warning 占位图没加  用户图片的点击方法还没实现（用户图片）
        [self.userButton sd_setBackgroundImageWithURL:urls forState:UIControlStateNormal];
        
        [headView addSubview:self.titleLabel];
        [headView addSubview:self.timerLabel];
        [headView addSubview:self.userButton];
        NSLog(@"##%f",HIGHT);
        
        self.tableView.tableHeaderView = headView;
        

        
        
//       [self.no1 getmodel2];
//        NSLog(@"%@",[[self.no1.trip_days objectAtIndex:0] nodes]);
//        
//        self.no2 = [[model2 alloc]init];
//        
//        [self.no2 getmodel3];
      //  NSLog(@"####%@",self.no2.nodes);
        
        
        
//        NSLog(@"数据传过来没：天数为%ld",no1.trip_days.count);
        
//        for (NSMutableDictionary *dic in no1.trip_days) {
//            model2 *no2 = [[model2 alloc]init];
//            [no2 setValuesForKeysWithDictionary:dic];
//            [self.AllDaysArr addObject:no2];
//        }
//        for (int i = 0; i < self.AllDaysArr.count; i++) {
//            for (NSDictionary *dict in self.AllDaysArr[i]) {
//                [array1 addObject:dict];
//            }
//            NSLog(@"数组元素下表为%ld的时候",array1.count);
//        }
        

//        NSLog(@"self.ALLDaysArr:%ld",self.AllDaysArr.count);


//        NSLog(@"总天数：%ld",self.AllDaysArr.count);
     //self.AllDaysArr里面装得是每一天的对象（区的个数就是此数组的个数）
        
        //获取第一天的数据
        //    model2 *mode = [self.AllDaysArr objectAtIndex:section];
//        NSMutableArray *arr = [NSMutableArray array];
//        for (NSMutableDictionary *dic1 in [[self.AllDaysArr objectAtIndex:section] nodes]) {
//            //        NSLog(@"这里是获取dic1中得所有数据%@",dic1);
//            //我们的遍历次数为我们这个dic1内的数组个数.
//            //dic1里面存储的是我们所有的数组，这个数组内包含了一个数组notes;
//            //每一次遍历，我们都初始化了一个数组，我们将dic1内的notes赋值给这个数组
//            
//            NSMutableArray *mutableArr = [dic1 objectForKey:@"notes"];
//            //我们遍历这个Key值为notes的数组
//            for (NSMutableDictionary *dididi in mutableArr) {
//                //            NSLog(@"%@",dididi);
//                //每遍历一次，我们获取了一个对象
//                model5 *mod= [[model5 alloc]init];
//                //每一次这个对象都会从这个遍历数组的字典当中获取数据
//                [mod setValuesForKeysWithDictionary:dididi];
//                //然后我们遍历一次，用数组添加一次这个对象
//                [arr addObject:mod];
//            }
//            
//            NSLog(@"最后一层数组的个数------%ld",arr.count);
//            //            model4 *no4 = [[model4 alloc]init];
//            //            [no4 setValuesForKeysWithDictionary:dic1];
//            //            [self.Allnodes addObject:no4];
//        }

        
//        NSLog(@"第一天由几部分构成%ld",self.Allnodes.count);

        //第一天里面由好几个部分组成 就是nodes的数组个数
//     for (int j = 0; j < self.Allnodes.count; j++) {
//            NSMutableArray *shuzu0 =  [[self.Allnodes objectAtIndex:j] notes];
//            for (NSMutableDictionary *dic4 in shuzu0) {
//                model5 *no5 = [[model5 alloc]init];
//                [no5 setValuesForKeysWithDictionary:dic4];
//                [self.Anotes addObject:no5]; //self.Anotes的个数就是第一天cell的row的个数
//            }
//
//        }
////        NSLog(@"%ld",self.Anotes.count);//这个数组中得内容包含第一天的row的数据
        //取第0个元素就是顶部描述的内容
        
//               NSInteger number = self.Allnodes.count;
        
        //
        
        
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

- (void)clickUser:(UIButton *)button
{
   
    UserViewController *user = [[UserViewController alloc]init];
    
    NSNumber *nu = [self.no1.user objectForKey:@"id"];;
    NSString *str = [NSString stringWithFormat:@"%@",nu];
    NSString *title = [self.no1.user objectForKey:@"name"];
    user.hidesBottomBarWhenPushed = YES;
    user.userID = str;
    user.gaTitle = title;
   
    [self.navigationController pushViewController:user animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
